package com.nisco.nio.channel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;

public class FileChannelTest {
    public static void main(String[] args)
        throws IOException {
        Charset charset = Charset.forName("UTF-8");//Java.nio.charset.Charset处理了字符转换问题。它通过构造CharsetEncoder和CharsetDecoder将字符序列转换成字节和逆转换。
        CharsetDecoder decoder = charset.newDecoder();

        System.out.println(System.getProperty("user.dir"));
        FileInputStream fis = new FileInputStream("nio/src/main/resources/aa.txt");

        FileChannel fileChannel = fis.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        CharBuffer charBuffer = CharBuffer.allocate(4);
        int i = 0;
        while (fileChannel.isOpen() && fileChannel.read(byteBuffer) != -1)
        {
            System.out.print("第" + (++i) + "次填充byte缓冲区,长度为:" + byteBuffer.position());
            byteBuffer.flip();
            decoder.decode(byteBuffer, charBuffer, true);
            System.out.println("  char decode use length=" + byteBuffer.position());

            charBuffer.flip();
            while (charBuffer.hasRemaining())
            {
                System.out.println("    转换为char缓冲区,charBuffer[" + charBuffer.position() + "]=" + charBuffer.get());
            }
            charBuffer.clear();
            System.out.println();
            byteBuffer.compact();  // 压缩，把未使用的压缩到前面
        }
    }
}
